<?php
defined('BASEPATH') OR exit('No direct script access allowed');

define("TOKEN", "51haopiao"); //TOKEN值
//define("TOKEN", "jgfyyk"); //TOKEN值
//define("APPID", "wx3b4f2f95e9778bf0"); //appid值
//define("APPSECRET", "dae63f1dc79c4d9b45d8f3162e7e0652"); //密钥
//
//define("APPID", "wx5672506691fea394"); //appid值
//define("APPSECRET", "a10b06bf4f7519152bad03311f212e65"); //密钥
//define("APPID", "wx6d03a0a1108166e1"); //appid值
//define("APPSECRET", "1d25a94f42f8167185b47a14d3bf4c18"); //密钥


class Welcome extends CI_Controller
{
	protected $CI;
	public function __construct()
	{

		parent::__construct();
		$this->CI =& get_instance();
		$this->load->model('Access_Token_Model');
		$this->load->helper('url_helper');
		$this->CI->load->library('AccessTokenClass');
	}
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 *        http://example.com/index.php/welcome
	 *    - or -
	 *        http://example.com/index.php/welcome/index
	 *    - or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{

		if (isset($_GET['echostr'])) {
		//	$this->expire_access_token();
			$this->valid();
		} else {

			$this->responseMsg();
			#$this->load->view('welcome_message');
		}
	}

	public function valid() {
		if(isset($_GET["echostr"])){
			$echoStr = $_GET["echostr"];
			if($this->checkSignature()){
				echo $echoStr;
				exit;
			}
		}
		exit;
	}

	public function setmenu(){
//		$access_token=$this->get_access_token();
		$access_token=$this->CI->accesstokenclass->get_access_token();
		echo $access_token;
		$this->set_wechat_menu($access_token);

	}

	public function set_wechat_menu($access_token){
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
//		$arr = array(
//			'button' =>array(
//				array(
//					"type"=>"view",
//					'name'=>urlencode("诉服中心"),
//					'url'=>'http://www.fddiaoyu.com/index.php/litigation_center'
//				),
//				array(
//					"type"=>"view",
//					'name'=>urlencode("法院新闻"),
//					'url'=>'http://www.fddiaoyu.com/index.php/article/list/2'
//				),
//				array(
//					"type"=>"view",
//					'name'=>urlencode("微信集群"),
//					'url'=>'http://www.fddiaoyu.com/index.php/weimix'
//				)
//
//			)
//		);

		$arr = array(
			'button' =>array(
				array(
					"type"=>"view",
					'name'=>urlencode("诉服中心"),
//					'url'=>'http://wechat.fddiaoyu.com/index.php/litigation_center'
					'url'=>'http://www.fddiaoyu.com/index.php/litigation_center'
				),
//				array(
//					"type"=>"view",
//					'name'=>urlencode("诉服中心"),
////					'url'=>'http://wechat.fddiaoyu.com/index.php/litigation_center'
//					'url'=>'http://wechat.fddiaoyu.com/index.php/litigation_center'
//				),
//				array(
//					"type"=>"view",
//					'name'=>urlencode("法院新闻"),
////					'url'=>'http://wechat.fddiaoyu.com/index.php/article/list/2'
//					'url'=>'http://www.fddiaoyu.com/index.php/article/list/2'
//				),
				array(
					"type"=>"view",
					'name'=>urlencode("司法公开"),
//					'url'=>'http://wechat.fddiaoyu.com/index.php/article/list/2'
					'url'=>'http://m.hzjgfy.gov.cn/'
				)
//				array(
//					"type"=>"view",
//					'name'=>urlencode("微信集群"),
////					'url'=>'http://wechat.fddiaoyu.com/index.php/weimix'
//					'url'=>'http://www.fddiaoyu.com/index.php/weimix'
//				)

			)
		);

		$jsondata = urldecode(json_encode($arr));
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$jsondata);
		curl_exec($ch);
		curl_close($ch);
	}

	private function checkSignature() {
		if(!isset($_GET["signature"])){
			return false;
		}
		$signature = $_GET["signature"];
		if(!isset($_GET["timestamp"])){
			return false;
		}
		$timestamp = $_GET["timestamp"];
		if(!isset($_GET["nonce"])){
			return false;
		}
		$nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ) {
			return true;
		} else {
			return false;
		}
	}


	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$RX_TYPE = trim($postObj->MsgType);

			switch($RX_TYPE)
			{
				case "text":
					$resultStr = $this->handleText($postObj);
					break;
				case "event":
					$resultStr = $this->handleEvent($postObj);
					break;
				default:
					$resultStr = "Unknow msg type: ".$RX_TYPE;
					break;
			}
			echo $resultStr;
		}else {
			echo "";
			exit;
		}
//					$time = time();
//			$textTpl = "<xml>
//                        <ToUserName><![CDATA[%s]]></ToUserName>
//                        <FromUserName><![CDATA[%s]]></FromUserName>
//                        <CreateTime>%s</CreateTime>
//                        <MsgType><![CDATA[%s]]></MsgType>
//                        <Content><![CDATA[%s]]></Content>
//                        <FuncFlag>0</FuncFlag>
//                        </xml>";
//			if($keyword == "?" || $keyword == "？")
//			{
//				$msgType = "text";
//				$contentStr = date("Y-m-d H:i:s",time());
//				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
//				echo $resultStr;
//			}
//		}else{
//			echo "";
//			exit;
//		}
	}

	public function handleEvent($object)
	{
		$contentStr = "";
		switch ($object->Event)
		{
			case "subscribe":
				//$contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号：zhuojinsz"."\n"."卓越锦绣，名城苏州，我们为您提供苏州本地生活指南，苏州相关信息查询，做最好的苏州微信平台。"."\n"."目前平台功能如下："."\n"."【1】 查天气，如输入：苏州天气"."\n"."【2】 查公交，如输入：苏州公交178"."\n"."【3】 翻译，如输入：翻译I love you"."\n"."【4】 苏州信息查询，如输入：苏州观前街"."\n"."更多内容，敬请期待...";
//			    $contentStr=array(array("Title" =>"欢迎关注浙江省高院",
//					"Description" =>"点击图片进入",
//					"PicUrl" =>"http://www.zjsfgkw.cn/Includes/images/home/1.jpg",
//					"Url" =>"http://www.fddiaoyu.com/index.php/article/show/about"));
				$contentStr=array(array("Title" =>"欢迎关注江干区人民法院",
					"Description" =>"点击图片进入",
					"PicUrl" =>"http://www.hzjgfy.gov.cn/Manage/Upload/Newsimages/2009_12/20091207135134109860.jpg",
					"Url" =>"http://wwww.fddiaoyu.com/index.php/article/show/about"));

				//$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
				break;
			default :
				$contentStr = "Unknow Event: ".$object->Event;
				break;
		}
		$resultStr = $this->transmitNews($object, $contentStr);
		return $resultStr;
	}

	private function transmitNews($object, $newsArray)
	{
		if(!is_array($newsArray)){
			return;
		}
		$itemTpl = "<item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    	</item>";
		$item_str = "";
		foreach ($newsArray as $item){
			$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
		}
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%s</ArticleCount>
		<Articles>
		$item_str</Articles>
		</xml>";

		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
		return $result;
	}

	public function responseText($object, $content, $flag=0)
	{
		$textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
		$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
		return $resultStr;
	}

	private function transmitText($object, $text)
	{

		$time = time();
		$textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
			</xml>";

			$msgType = "text";
			$contentStr = $text;
			$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, $time, $msgType, $contentStr);

		return $resultStr;
	}
	private function receiveEvent($object){
		$content = "";
		switch ($object->Event)
		{
			case "subscribe":
				$content = "欢迎关注方倍工作室 ";
//				$content = array();
//				$content[] = array("Title" =>"欢迎关注浙江省高院",
//					"Description" =>"点击图片进入",
//					"PicUrl" =>"http://www.fddiaoyu.com/resources/image/zhejianggaoyuan.jpg",
//					"Url" =>"http://www.fddiaoyu.com/index.php/article/show/about");
				//$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
				break;
			case "unsubscribe":
				$content = "取消关注";
				break;
			case "SCAN":
				$content = "扫描场景 ".$object->EventKey;
				break;
			case "CLICK":
				switch ($object->EventKey)
				{
					case "COMPANY":
						$content = array();
						$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
						break;
					default:
						$content = "点击菜单：".$object->EventKey;
						break;
				}
				break;
			case "LOCATION":
				$content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
				break;
			case "VIEW":
				$content = "跳转链接 ".$object->EventKey;
				break;
			case "MASSSENDJOBFINISH":
				$content = "消息ID：".$object->MsgID."，结果：".$object->Status."，粉丝数：".$object->TotalCount."，过滤：".$object->FilterCount."，发送成功：".$object->SentCount."，发送失败：".$object->ErrorCount;
				break;
			default:
				$content = "receive a new event: ".$object->Event;
				break;
		}
		$result='';
		if(is_array($content)){
			if (isset($content[0])){
				$result = $this->transmitNews($object, $content);
			}else if (isset($content['MusicUrl'])){
				$result = $this->transmitMusic($object, $content);
			}
		}else{
			$result = $this->transmitText($object, $content);
		}
		return $result;
	}



	public function get_access_token(){
		$access_token_array=$this->Access_Token_Model->get_sys_access_token();
		if(empty($access_token_array)||count($access_token_array)==0){
			$accessToken=$this->get_new_access_token();
			$data=array(
				'gmt_create'=>date("Y-m-d H:i:s" ,time()),
				'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
				'token_type'=>'1',
				'expire_time'=>date("Y-m-d H:i:s" ,time()+7200),
				'access_tokens'=>$accessToken
			);
			$result=$this->Access_Token_Model->insert_access_token($data);
			if($result){
				return $accessToken;
			}else{
				return "";
			}
		}else{
			$access_token_row=$access_token_array[0];
			$expire_time=$access_token_row['expire_time'];
			echo  'expire_time is:'.$expire_time;
			if(strtotime($expire_time)<time()){
				$this->expire_access_token();
			}else{
				return $access_token_row['access_tokens'];
			}
		}
	}
	public function get_new_access_token(){
		$token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
		$res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
//echo $res;
		$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
		$access_token = $result['access_token'];
		return $access_token;
	}
	public function  expire_access_token(){
		$access_token_row=$this->Access_Token_Model->get_access_token();
		if(!isset($access_token_row)){
			return false;
		}
		$data=array(
			'id'=>$access_token_row['id'],
			'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
			'expire_time'=>date("Y-m-d H:i:s" ,time()+7200)
		);
		$result=$this->Access_Token_Model->update_access_token($data);
		if($result){
			return true;
		}else{
			return false;
		}
	}
}


